package com.iseastar.login;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Paint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.telephony.SmsMessage;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.TextView;

import com.iseastar.BaseActivity2;
import com.iseastar.dianxiaosan.model.Const;
import com.iseastar.guojiang.MainActivity;
import com.iseastar.guojiang.app.AppCache;
import com.iseastar.guojiang.consts.MsgID;
import com.iseastar.guojiang.dialog.DialogMgr;
import com.iseastar.guojiang.logic.AppHttp;
import com.iseastar.guojiang.logic.JSON;
import com.iseastar.guojiang.model.ReqResult;
import com.iseastar.guojiang.model.UserBean;
import com.iseastar.guojiang.tools.TextWatcherExt;
import com.iseastar.guojiang.view.DeleteEditText;
import com.shouhuobao.station.R;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import droid.frame.activity.title.TitleRes;
import droid.frame.utils.lang.Str;

/**
 * 火箭侠登录
 *
 * @author HuXinDan<br>
 * 2016-11-22上午11:04:44
 */
public class LoginActivity extends BaseActivity2 implements OnClickListener {
    private BroadcastReceiver smsReceiver;
    private IntentFilter smsFilter;

    private TextView mLoginGetCodeTV;//获取验证码按钮
    private DeleteEditText mLoginCodeEdit;//验证码输入框
    private TextView mLoginTV;//登录按钮
    private DeleteEditText mLoginPhoneEdit;//手机号输入框
    private String phone;//输入的手机号
    private String code;//输入的验证码

    private int clickCount = 1;//点击次数

    @SuppressLint("MissingSuperCall")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        registerSmsReceiver();
    }

    @Override
    protected void findViewById() {
        setContentView(R.layout.login_courier);
        super.findViewById();
        getAppTitle().setTitle(null, new TitleRes("登录"), null);
        mLoginPhoneEdit = (DeleteEditText) findViewById(R.id.login_phone_edit);
        mLoginCodeEdit = (DeleteEditText) findViewById(R.id.login_code_edit);
        mLoginGetCodeTV = (TextView) findViewById(R.id.login_code_tv);
        mLoginGetCodeTV.setOnClickListener(this);
        mLoginTV = (TextView) findViewById(R.id.login_tv);
        mLoginTV.setOnClickListener(this);
        TextView mJoinCourierTV = (TextView) findViewById(R.id.join_courier);
        mJoinCourierTV.setOnClickListener(this);
        TextView mExplainTV = (TextView) findViewById(R.id.explain_tv);
        mExplainTV.setOnClickListener(this);
        mExplainTV.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);//下划线
        mExplainTV.getPaint().setAntiAlias(true);//抗锯齿
        findViewById(R.id.login_lianmeng).setOnClickListener(this);
        //手机号输入框监听
        mLoginPhoneEdit.addTextChangedListener(new droid.frame.view.TextWatcherExt(1) {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // 可以修改手机号, 但是必须等到30s以后才可以重新发送
                if (s.length() == 13 && recLen == 30) {
                    mLoginGetCodeTV.setEnabled(true);
                    mLoginGetCodeTV.setBackgroundResource(R.drawable.app_courier_press_shape);
                    if (mLoginCodeEdit.getText().length() >= 4) {
                        mLoginTV.setEnabled(true);
                    } else {
                        mLoginTV.setEnabled(false);
                    }
                } else {
                    mLoginTV.setEnabled(false);
                    mLoginGetCodeTV.setEnabled(false);
                }
            }
        });
        //验证码输入监听
        mLoginCodeEdit.addTextChangedListener(new TextWatcherExt() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.length() >= 4) {
                    if (mLoginPhoneEdit.getText().length() == 13) {
                        mLoginTV.setEnabled(true);
                    } else {
                        mLoginTV.setEnabled(false);
                    }
                } else {
                    mLoginTV.setEnabled(false);
                }
                // 输入完寄件码，自动验证
                if (s.length() == 4) {
                    loginVerify();
                }
            }
        });

    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    public void onClick(View v) {
        Intent intent = null;
        switch (v.getId()) {
            // 登录
            case R.id.login_tv:
                loginVerify();
                break;
            //获取验证码
            case R.id.login_code_tv:
                if (mLoginPhoneEdit.getText().length() == 13) {
                    phone = mLoginPhoneEdit.getText().toString().replace(" ", "");
                    showLoadingDialog(null);
                    if (clickCount > 2) {
                        AppHttp.getInstance().courierGetSMSVerifyCode(phone, "1");
                    } else {
                        AppHttp.getInstance().courierGetSMSVerifyCode(phone, "");
                    }
                } else {
                    showToast("手机号输入有误");
                }
                break;
            // 加入火箭侠
            case R.id.join_courier:
                intent = new Intent();
                intent.setClass(getContext(), RegisterCourierActivity.class);
                startActivityForResult(intent, 1505);
                break;
            //火箭联盟登录
            case R.id.login_lianmeng://
                intent = new Intent();
                intent.setClass(getContext(), LoginChooseActivity.class);
                startActivityForResult(intent, 1506);
                break;
            default:
                break;
        }
    }

    @Override
    public boolean handleMessage(Message msg) {
        switch (msg.what) {
            // 发送验证码
            case MsgID.courier_send_verifyNum:
                cancelLoadingDialog();
                ReqResult<?> result = JSON.parser(msg.obj);
                if (checkLoginStatus(result)) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            countDownStart();
                        }
                    });
                } else {
                    showToast(result.getMessage());
                }
                return false;
            //火箭侠登录
            case MsgID.courier_login_verify_code:
                cancelLoadingDialog();
                final ReqResult<UserBean> result1 = JSON.parser(msg.obj, UserBean.class);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        AppCache.setUser(null);
                        AppCache.setOrder(null);
                        AppCache.setStationOpenInfoBean(null);
                        if (checkLoginStatus(result1)) {
                            UserBean userBean = result1.getResult();
                            if (userBean != null) {
                                if (isEmpty(userBean.getPhone())) {
                                    userBean.setPhone(phone);
                                }
                                AppCache.setUser(userBean);
                                if (userBean.getState() == Const.CourierRegisterStatus.RegisterOkStatus) {
                                    Intent intent = new Intent();
                                    intent.setClass(LoginActivity.this, MainActivity.class);
                                    startActivity(intent);
                                    setResult(RESULT_OK);
                                    finish();
                                } else {
                                    DialogMgr.courierLoginDialog(getContext(), userBean);
                                }

                            }
                        } else {
                            showToast(result1.getMessage());
                        }
                    }
                });

                return true;
            default:
                return super.handleMessage(msg);
        }
    }

    private int recLen = 30;
    private boolean isStart;
    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            if (recLen == 1) {
                isStart = false;
                recLen = 30;
                mLoginGetCodeTV.setEnabled(true);
                mLoginGetCodeTV.getPaint().setFlags(0);
                mLoginGetCodeTV.setText("重新获取");
            }
            if (recLen == 29) {
                clickCount++;
                showToast("短信验证码已发送");
            }
            if (isStart) {
                recLen--;
                mLoginGetCodeTV.setEnabled(false);
                mLoginGetCodeTV.getPaint().setFlags(0);
                mLoginGetCodeTV.setBackgroundResource(R.drawable.app_courier_press_shape);
                mLoginGetCodeTV.setText(recLen + "秒后重新发送");
                getHandler().postDelayed(this, 1000);
            }
        }
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK && (requestCode == 1505 || requestCode == 1506)) {
            finish();
        }
    }

    /**
     * 登录验证
     */
    private void loginVerify() {
        phone = mLoginPhoneEdit.getText().toString().replace(" ", "");
        code = mLoginCodeEdit.getText().toString();
        if (Str.isEmpty(phone)) {
            showToast("请输入手机号，获取验证码");
            return;
        }
        showLoadingDialog(null);
        AppHttp.getInstance().courierLoginVerifyCode(phone, code, 0);
    }

    private void countDownStart() {
        getHandler().postDelayed(runnable, 1000);
        isStart = true;
        mLoginGetCodeTV.setEnabled(false);
        mLoginCodeEdit.requestFocus();
        InputMethodManager imm = (InputMethodManager) mLoginCodeEdit.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.toggleSoftInput(0, InputMethodManager.SHOW_FORCED);
    }

    public Handler smsHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            if (msg.what == 1) {
                mLoginCodeEdit.setText(msg.obj.toString());
            }
        }
    };

    private void registerSmsReceiver() {
        smsFilter = new IntentFilter();
        smsFilter.addAction("android.provider.Telephony.SMS_RECEIVED");
        smsFilter.setPriority(Integer.MAX_VALUE);
        smsReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                Object[] objs = (Object[]) intent.getExtras().get("pdus");
                for (Object obj : objs) {
                    byte[] pdu = (byte[]) obj;
                    SmsMessage sms = SmsMessage.createFromPdu(pdu);
                    String message = sms.getMessageBody();
                    String from = sms.getOriginatingAddress();
                    if (!TextUtils.isEmpty(from)) {
                        String code = patternCode(message);
                        if (!TextUtils.isEmpty(code)) {
                            Message msg = new Message();
                            msg.what = 1;
                            msg.obj = code;
                            smsHandler.sendMessage(msg);
                        }
                    }
                }
            }
        };
        registerReceiver(smsReceiver, smsFilter);
    }

    /**
     * 匹配短信中间的6个数字（验证码等）
     */
    private String patternCode(String patternContent) {
        if (TextUtils.isEmpty(patternContent)) {
            return null;
        }
        Pattern p = Pattern.compile("(?<!\\d)\\d{4}(?!\\d)");
        Matcher matcher = p.matcher(patternContent);
        if (matcher.find()) {
            return matcher.group();
        }
        return null;
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (smsReceiver != null) {
            unregisterReceiver(smsReceiver);
        }
        if (runnable != null) {
            getHandler().removeCallbacks(runnable);
        }
    }
}



